<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Multiplayer Snake</title>
    <script src="jquery-2.1.0.min.js"></script>
	<script src="snake.js"></script>
    <script>

	//GameState Manager-------------------------------------------------
	
	function GameState (food_image_url) {
		this.snakeBoard = new Snake.SnakeBoard(60,40);
		this.snakes = [];
		this.server_msg = "";
		this.food = undefined;
		this.foodImage = undefined;
		if(food_image_url) {
			this.foodImage = new Image();
			this.foodImage.src = food_image_url;
		}

		
	}
	
	GameState.prototype.setup = function (boardState) {
		this.snakes = [];
		this.snakeBoard.clear();
		for(var i=0; i<boardState.snakes.length; i++) {
			var snake = boardState.snakes[i];
			testSnake3 = new Snake.Snake(snake.name, this.snakeBoard, snake.colour, snake.segments, snake.direction);
			gameState.addSnake(testSnake3);
		}
		
		this.food = new Snake.Food(boardState.food.x, boardState.food.y, this.snakeBoard);
	};

	GameState.prototype.render = function (context) {
		/*
		context.setTransform(1, 0, 0, 1, 0, 0);
		context.lineWidth = 0.002;
		context.stroke();
		context.scale(canvas.width, canvas.height);
		this.snakeBoard.render(context);
		*/

		context.setTransform(1, 0, 0, 1, 0, 0);
		context.lineWidth = 0.002;
		context.stroke();
		context.scale(canvas.width, canvas.height);
		var cellSizeX = 1.0 / this.snakeBoard.width;
		var cellSizeY = 1.0 / this.snakeBoard.height;
		for(var s=0; s<this.snakes.length; s++){
			for (var c=0; c<this.snakes[s].segments.length; c++) {
				context.beginPath();
				var x = this.snakes[s].segments[c].x;
				var y = this.snakes[s].segments[c].y;
				context.rect(x * cellSizeX, y * cellSizeY, cellSizeX, cellSizeY);
				context.fillStyle = this.snakes[s].colour;
				context.fill();
			}
		}

		context.setTransform(1, 0, 0, 1, 0, 0);
		if (this.food && this.foodImage) {
			context.drawImage(this.foodImage, this.food.x*10, this.food.y*10);
		}

		var xp = context.canvas.width / 2;
		var yp = context.canvas.height / 2 + 10;

		context.font = '30pt Calibri';
		context.textAlign = 'center';
		context.fillStyle = 'black';
		context.fillText(this.server_msg, xp, yp);

	}
	
	GameState.prototype.gameOver = function () {
	};
	
	GameState.prototype.changeSnakeDirection = function (name, direction) {
		for(var s=0; s<this.snakes.length; s++) {
			if (this.snakes[s].name == name) {
				this.snakes[s].changeDirection(direction);
			}
		}
	};
	
	GameState.prototype.tick = function () {
		for(var i=0; i<this.snakes.length; i++) {
			this.snakes[i].tick();
		}
	};
	
	GameState.prototype.addSnake = function (snake) {
		this.snakes.push(snake);
	};
	
	//NetManager--------------------------------------------------------
	
	function NetManager (gameState) {
		this.gameState = gameState;
		this.connected = false;
		this.authed = false;
		this.username = "";
		this.password = "";
		this.gameState.server_msg = "Connecting to server...";
		
		//this.connection = new WebSocket("ws://whosondrinks.info:81");
		this.connection = new WebSocket("ws://localhost:81");
		this.connection.netManager = this;
		
		this.connection.onopen = function(){
			console.log('Connection open!');
			this.netManager.gameState.server_msg = "Connected";
			this.netManager.connected = true;
		};
		
		this.connection.onclose = function() {
			console.log('Connection closed!');
			this.netManager.gameState.server_msg = "Server connection closed :(";
			this.netManager.connected = false;
		};
		
		this.connection.onerror = function(error) {
			console.log('Error: ',error);
			this.netManager.gameState.server_msg = "Server connection error :(";
			this.netManager.connected = false;
		};
		
		this.connection.onmessage = function(e) {
			var netManager = this.netManager;
			var data = JSON.parse(e.data);
            if (data.message == "auth") {
				netManager.authed = data.auth;
				if (data.auth) {
					authed();
				}
			} else if (data.message == "direction") {
				netManager.gameState.changeSnakeDirection(data.name, data.direction)
			} else if (data.message == "boardState") {
				netManager.gameState.setup(data.boardState);
			} else if (data.message == "playerState") {
				$("#players").empty();
				
				for(var player in data.players) {
					var colour = data.players[player].colour;
					var state = "Offline";
					if (data.players[player].joined) {
						state = "Connected";
					}
					if (data.players[player].ready){
						state = "Ready";
					}
					$("#players").append('<tr><td class="employee" style="color:'+colour+';font-weight:bold;">'+player+'</td><td class="request">Loses: '+data.players[player].loses+'</td><td class="request">'+state+'</td></tr>');
				}
			} else if (data.message == "tick") {
				netManager.gameState.tick();
			} else if (data.message == "gameOver") {
				netManager.gameState.gameOver();
				if (data.loser){
					$("#game_over_message").html(data.loser + " is on Drinks");
				}
			} else if (data.message == "server_msg") {
				netManager.gameState.server_msg = data.server_msg;
			}
		}
	}
	
	NetManager.prototype.login = function (username, password) {
		this.username = username;
		this.password = password;
		this.sendObject({message: "auth", username: this.username, password: this.password});
	};
	
	NetManager.prototype.ready = function (state) {
		this.sendObject({message: "ready", username: this.username, password: this.password, ready: state});
	};
	
	NetManager.prototype.move = function (move) {
		this.sendObject({message: "move", username: this.username, password: this.password, direction: move});
	};
	
	NetManager.prototype.sendObject = function ( object ) {
		console.log("sending", object);
		if (this.connected) {
			this.connection.send(JSON.stringify(object));
		}
	};
	
	//Key handler-------------------------------------------------------
	$(document).bind("keydown", function(e){
        if (netManager.authed) {
          switch(e.keyCode)
            {
            //Left
            case 37:
            netManager.move(Snake.Snake.directions.LEFT);
            break;
            
            //Up
            case 38:
            netManager.move(Snake.Snake.directions.UP);
            break;

            //Right
            case 39:
            netManager.move(Snake.Snake.directions.RIGHT);
            break;
            
            //Down
            case 40:
            netManager.move(Snake.Snake.directions.DOWN);
            break;
            }
          }
        });
	
	//Globals-----------------------------------------------------------
	
	var snakeBoard;
	var netManager;
	var canvas;
	var context;
	
	
	function SetupGame() {
		
		console.log("Creating stateManager...");
		gameState = new GameState("images/fruit.png");
		
		console.log("Creating netManager...");
		netManager = new NetManager(gameState);
		
		console.log("Hooking Canvas...");
		canvas = $("#canvas")[0];
		
		context = canvas.getContext("2d");
		console.log("Setup Complete...");
	}
	
	var endTime = new Date(2014, 8, 19, 15, 0, 0, 0);
	
	function Run() {
		context.clearRect(0,0,canvas.width, canvas.height);

		gameState.render(context);



		var currentTime = Date.now();
        var remaining = endTime - currentTime;
		
		if (remaining > 0) {
				var timeText = "";
				var hours = Math.floor(remaining / (1000*60*60));
				var minutes = (Math.floor(remaining / (1000*60))) % 60;
				var seconds = (Math.floor(remaining / (1000))) % 60;
			   
				if (hours > 0) { timeText += hours + " hours ";}
				if (minutes > 0) { timeText += minutes + " minutes ";}
				if (seconds > 0 && hours < 1) { timeText += seconds + " seconds";}
			   
				$("#timer").html("<h3>"+timeText+"</h3>");
			  
			} else {
				$("#timer").html("<h3>Drinks Time</h3>");
        }
		
		setTimeout(Run, 1000/60);
	}

	
	
	//interface methods
	function authMe () {
		var username = $("#username").val();
        var password = $("#auth").val();
        netManager.login(username, password);
	}

	function authed () {
		$("#authdiv").html('<button type="button" onclick="netManager.ready(true)">Ready</button><button type="button" onclick="netManager.ready(false)">Un-Ready</button>'); 
	}

	$().ready(
		function () {
			
			SetupGame();
			Run();
		}
	);
    </script>
  </head>
  <body>
  	<canvas id="canvas" width="600" height="400" style="border: 1px solid black;">
    </canvas>
    <div id="authdiv">
		<div>Name:<input id="username" style="width:55px"> Auth:<input id="auth" style="width:55px"><button onclick="authMe();">Auth Me</button></div>
	</div>
	<table id="players">
	</table>
  	<span id="game_over_message">
  	</span>
  </body>
</html>

